<?php

namespace app\index\controller;

use app\common\model\Company as CompanyModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume;
use app\common\model\Resume as ResumeModel;
use app\common\model\JobsDeliveryResume as DeliveryModel;
use app\common\model\ResumeDownloaded as ResumeDownloadedModel;
use app\common\model\ResumeEmploymentIntention as ResumeEmploymentIntentionModel;
use app\common\model\UserTimer as UserTimerModel;
use think\facade\Cache;
use think\facade\View;

class DataScreen extends Base

{

    public function index()
    {
        $token = request()->get('token');

        // 判断是否存在token
        if (!$this->checkToken($token)) {
            return '<div style="width: 100%; height: 100vh;display: flex;justify-content: center;align-items: center; font-size: 48px; color: #666;">参数错误，请联系网站管理员获取正确的访问链接！</div>';
        }

        $title = config('xy_data_screen.screen_title');
        View::assign('token', $token);
        View::assign('title', $title);
        return view();
    }



    public function api()
    {

        $token = request()->get('token');

        // 判断是否存在token
        if (!$this->checkToken($token)) {
            return json(['code' => -1, 'msg' => '参数错误：未提供token！']);
        }

        // 入驻企业，岗位数量，用人需求，求职人数

        $companiesNumber = CompanyModel::where('attestation', 3)->count('id');
        $jobsNumber = JobsModel::alias('job')->join('company com', 'com.id=job.company_id')->where('examine&status', '=', 1)->count();
        $recruitsNumber = JobsModel::alias('job')->join('company com', 'com.id=job.company_id')->where('examine&status', '=', 1)->sum('number_of_recruiters');
        $resumesNumber = ResumeModel::where('privacy&examine', '=', 1)->whereNull('delete_time')->count();

        //职位总浏览量
        $jobViewNumber=JobsModel::sum('view');
        $jobViewNumber+=config('xy_data_screen.web_site_count_jobViews') ?? 0;

        //投递总数
        $jobResumesNumber=JobsDeliveryResume::count();
        $jobResumesNumber+=config('xy_data_screen.web_site_count_jobResumes') ?? 0;


        // 加上模拟数据
        $companiesNumber += config('basic.web_site_count_company') ?? 0;
        $jobsNumber += config('basic.web_site_count_jobs') ?? 0;
        // 假定每个岗位需求人数最少2个
        // $recruitsNumber += $jobsNumber * 2;
        $resumesNumber += config('basic.web_site_count_resume') ?? 0;

        // 时间区间下界，上个月的今天
        $timeMinLimit = strtotime(date('Y-m-d 00:00:00', strtotime('last month')));

        // 刷新简历(暂时弃用)
        // $resumeActivity = ResumeModel::where('refresh_time', '>=', $timeMinLimit)
        //     ->group('date')
        //     ->field([
        //         "FROM_UNIXTIME( refresh_time, '%Y/%m/%d' )" => 'date',
        //         'COUNT(*)' => 'number'
        //     ])
        //     ->select()
        //     ->toArray();

        $userRegister = UserTimerModel::alias('timer')
            ->join('user_info info', 'info.uid=timer.uid')
            ->where('info.role_type', 0)
            ->where('register_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( register_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $userLoginActivity = UserTimerModel::alias('timer')
            ->join('user_info info', 'info.uid=timer.uid')
            ->where('info.role_type', 0)
            ->where('login_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( login_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $createResumeActivity = ResumeModel::where('create_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( create_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $deliveryActivity = DeliveryModel::where('create_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( create_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $companyRegisterActivity = UserTimerModel::alias('timer')
            ->join('user_info info', 'info.uid=timer.uid')
            ->where('info.role_type', 1)
            ->where('register_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( login_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $companyLoginActivity = UserTimerModel::alias('timer')
            ->join('user_info info', 'info.uid=timer.uid')
            ->where('info.role_type', 1)
            ->where('login_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( login_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $jobActivity = JobsModel::alias('job')
            ->join('company com', 'com.id=job.company_id')
            ->where('examine&status', '=', 1)
            ->where('job.refresh_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( job.refresh_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $downloadResumeActivity = ResumeDownloadedModel::alias('download')
            ->join('resume resume', 'resume.id=download.resume_id')
            ->where('download.create_time', '>=', $timeMinLimit)
            ->group('date')
            ->field([
                "FROM_UNIXTIME( download.create_time, '%Y/%m/%d' )" => 'date',
                'COUNT(*)' => 'number'
            ])
            ->select()
            ->toArray();

        $timeLine = [];

        // 取当前时间作为时间段终点

        $endTime = time();

        // 取前一个月作为时间段起点

        $startTime = $timeMinLimit;

        for (; $startTime <= $endTime; $startTime += 86400) {
            $timeLine[] = date('Y/m/d', $startTime);
        }



        $time = time();

        // 性别占比

        $_sexRate = ResumeModel::group('sex')
            ->field([
                "( CASE WHEN sex = 1 THEN '男' WHEN sex = 2 THEN '女' ELSE '未公开' END )" => 'sex',
                'COUNT(id)' => 'number'
            ])
            ->select()
            ->toArray();


        $sexRate = [];

        foreach ($_sexRate as $key => $value) {
            $sexRate[] = ['name' => $value['sex'], 'value' => $value['number']];
        }

        // 年龄分布

        $_ageRate = ResumeModel::group('age')
            ->field([
                "( CASE WHEN age > " .
                    ($time - 86400 * 365 * 20) .
                    " AND age < " .
                    ($time - 86400 * 365 * 16) .
                    " THEN '16-20岁' WHEN age > " .
                    ($time - 86400 * 365 * 30) .
                    " AND age < " . ($time - 86400 * 365 * 21) .
                    " THEN '21-30岁'  WHEN age > " .
                    ($time - 86400 * 365 * 31) .
                    " AND age < " .
                    ($time - 86400 * 365 * 40) .
                    " THEN '31-40岁' WHEN age > " .
                    ($time - 86400 * 365 * 41) .
                    "  AND age < " . ($time - 86400 * 365 * 50) .
                    " THEN '41-50岁' ELSE '其他' END )" => 'age_region',
                'COUNT(id)' => 'number'
            ])
            ->group('age_region')
            ->order('age_region')
            ->select()
            ->toArray();


        $ageRate = [];

        foreach ($_ageRate as $key => $value) {
            $ageRate[] = ['name' => $value['age_region'], 'value' => $value['number']];
        }

        // 学历分布

        $_eduRate = ResumeModel::group('edu_level')
            ->field([
                "(CASE WHEN educational_background=1 THEN '初中及以下' WHEN educational_background=2 THEN '中专/中技' WHEN educational_background=2 THEN '高中' WHEN educational_background=3 THEN '大专' WHEN educational_background=5 THEN '本科' WHEN educational_background=6 THEN '硕士' WHEN educational_background=7 THEN '博士' ELSE '其他' END )" => 'edu_level',
                'COUNT(id)' => 'number'
            ])
            ->select()
            ->toArray();

        $eduRate = [];

        foreach ($_eduRate as $key => $value) {
            $eduRate[] = ['name' => $value['edu_level'], 'value' => $value['number']];
        }

        $_workExpRate = ResumeModel::group('work_exp')
            ->field([
                "( CASE WHEN work_experience_time > 1606147200 THEN '应届生' WHEN work_experience_time < 1606147199 AND work_experience_time > 1574524800 THEN '一年' WHEN work_experience_time < 1574524800 AND work_experience_time > 1542988800 THEN '两年' WHEN work_experience_time < 1574524800 THEN '三年及以上' ELSE '其他' END )" => 'work_exp',
                'COUNT(id)' => 'number'
            ])
            ->select()
            ->toArray();

        $workExpRate = [];

        foreach ($_workExpRate as $key => $value) {
            $workExpRate[] = ['name' => $value['work_exp'], 'value' => $value['number']];
        }

        // 意向行业

        $_industryRate = ResumeEmploymentIntentionModel::alias('res_emp')
            ->join('company_industry industry', 'industry.id=res_emp.industry_id')
            ->field([
                'industry.title' => 'industry_title',
                'COUNT(res_emp.id)' => 'number'
            ])
            ->group('industry_title')
            ->select()
            ->toArray();

        $industryRate = [];

        foreach ($_industryRate as $key => $value) {
            $industryRate[] = ['name' => $value['industry_title'], 'value' => $value['number']];
        }

        $_companyNatureRate = CompanyModel::alias('com')
            ->join('status_alias alias', "alias.value=com.nature AND alias.alias='company/nature'")
            ->group('alias.title')
            ->field([
                'alias.title' => 'nature',
                'COUNT(com.id)' => 'number'
            ])
            ->select()
            ->toArray();

        $companyNatureRate = [];

        foreach ($_companyNatureRate as $key => $value) {
            $companyNatureRate[] = ['name' => $value['nature'], 'value' => $value['number']];
        }

        $_companySizeRate = CompanyModel::alias('com')
            ->join('status_alias alias', "alias.value=com.size_type AND alias.alias='company/size_type'")
            ->group('alias.title')
            ->field([
                'alias.title' => 'size',
                'COUNT(com.id)' => 'number'
            ])
            ->select()
            ->toArray();

        $companySizeRate = [];

        foreach ($_companySizeRate as $key => $value) {
            $companySizeRate[] = ['name' => $value['size'], 'value' => $value['number']];
        }

        $jobTopList = JobsModel::alias('job')
            ->join('jobs_delivery_resume delivery', 'delivery.jobs_id=job.id')
            ->where('job.examine&job.status', '=', 1)
            ->field([
                'job.title' => 'title',
                'COUNT(*)' => 'delivery_number'
            ])
            ->group('title')
            ->order('delivery_number', 'DESC')
            ->limit(50)
            ->select()
            ->toArray();

        $companyTopList = CompanyModel::alias('com')
            ->join('jobs_delivery_resume delivery', 'delivery.company_id=com.id')
            ->where('com.attestation', '=', 3)
            ->field([
                'com.title' => 'company_name',
                'COUNT(*)' => 'delivery_number'
            ])
            ->order('delivery_number', 'DESC')
            ->group('com.id')
            ->limit(50)
            ->select()
            ->toArray();

        $deliveryList = DeliveryModel::alias('delivery')
            ->join('jobs job', 'job.id=delivery.jobs_id')
            ->join('resume resume', 'resume.id=delivery.resume_id')
            ->where('delivery.status', 0)
            ->field([
                'resume.name' => 'resume_name',
                'job.title' => 'job_name',
                'delivery.create_time' => 'delivery_time',
            ])
            ->order('delivery.create_time', 'DESC')
            ->limit(50)
            ->select()
            ->toArray();

        $result = [
            'code' => 0,
            'data' => [
                'companies_number' => $companiesNumber,
                'jobs_number' => $jobsNumber,
                'recruits_number' => $recruitsNumber,
                'resumes_number' => $resumesNumber,

                // 刷新简历(暂时弃用)
                // 'resume' => $resumeActivity,

                'user_register' => $userRegister,
                //职位总浏览量
                'jobViewNumber' => $jobViewNumber,
                //简历投递总量
                'jobResumesNumber'=>$jobResumesNumber,
                'user_login' => $userLoginActivity,
                'create_resume' => $createResumeActivity,
                'delivery' => $deliveryActivity,
                'company_register' => $companyRegisterActivity,
                'company_login' => $companyLoginActivity,
                'job' => $jobActivity,
                'download_resume' => $downloadResumeActivity,
                'time_line' => $timeLine,
                'sex' => $sexRate,
                'age' => $ageRate,
                'edu' => $eduRate,
                'work_exp' => $workExpRate,
                'industry' => $industryRate,
                'nature' => $companyNatureRate,
                'size' => $companySizeRate,
                'company_rank' => $companyTopList,
                'job_rank' => $jobTopList,
                'delivery_list' => $deliveryList
            ],
            'msg' => '获取成功'
        ];

        return json($result);
    }



    private function checkToken($token)
    {
        $systemToken = Cache::get('data_screen/token');
        // if (empty($token) || $token != $systemToken) {
        //     return false;
        // }
        return !(empty($token) || $token != $systemToken);
    }
}
